

#include "psdlite.h"


#include <iostream>
#include <string>
#include <sstream>

using namespace std;
using namespace psdlite;


#include "gfxconv.h"


image_info image;



u32 CountPixels(u16 i){
	u32 n, cnt = 0;
	u32 size = image.layers[i].width * image.layers[i].height;
	for (n=0; n<size; n++){
		if ((image.layers[i].data[n]>>24) >= 100) cnt++;
	}
	
	return cnt;
}


u8 GetType(u16 i){
	if (image.layers[i].visible) return TYPE_IMAGE;
	else{
		u32 count = CountPixels(i);
		if (count == 1) return TYPE_HOTSPOT;
		else return TYPE_COLINFOS;
	}
}



int main(int argc, char** argv){

	if (argc < 2) exit(0);
	layered_image img;
	load_layered_image(img,argv[1]);

	image.nb_layers = (u32) img.layers_.size();
	image.width = (u16) img.size_.x;
	image.height = (u16) img.size_.y;
	image.layers = new layer_info[image.nb_layers];
	if (!image.layers){
		cout << "Memory allocation problem... Can't continue\n";
		exit(0);
	}


	for (u32 i = 0; i < image.nb_layers; i++){

		layer& l = img.layers_[i];

		image.layers[i].name = l.name_.c_str();

		image.layers[i].x = l.offs_.x;
		image.layers[i].y = l.offs_.y;

		image.layers[i].width = l.data_.get_size().x;
		image.layers[i].height = l.data_.get_size().y;

		image.layers[i].opacity = l.opacity_;
		image.layers[i].visible = !(l.flags_&2);

		bitmap& b = l.data_;
		vi2 s = b.get_size();
		image.layers[i].data = new u32[s.x * s.y];
		if (!image.layers[i].data){
			if (i){
				do {
					i--;
					delete[] image.layers[i].data;
				} while (i);
			}
			cout << "Memory allocation problem... Can't continue\n";
			exit(0);
		}

		u16 count = 0;
		for (u16 y = 0; y != s.y; y++){
			for (u16 x = 0; x != s.x; x++){
				pixel p = b.get_pixel(x, y);
				image.layers[i].data[count++] = p.r()|(p.g()<<8)|(p.b()<<16)|(p.a()<<24);
			}
		}

	}
	
	image.nb_images = image.nb_hotspots = image.nb_colinfos = 0;
	
	for (u32 i=0; i<image.nb_layers; i++) {
		image.layers[i].type = GetType(i);
		if (image.layers[i].type == TYPE_IMAGE) image.nb_images++;
		else if (image.layers[i].type == TYPE_HOTSPOT) image.nb_hotspots++;
		else image.nb_colinfos++;
	}

	Convert(argc, argv);

	for (u32 i = 0; i < image.nb_layers; i++) delete[] image.layers[i].data;
	delete[] image.layers;

	return 0;
}
